Skip to main content

Diameter of Binary Tree

Question

What is the longest path between two nodes in a binary tree?

Example 1
Given the binary tree:

1
/ \
2 3
/ \
4 5

The diameter of the binary tree is 3.

Solution

all//Diameter of Binary Tree.py


# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def diameterOfBinaryTree(self, root):
self.ans = 1
def depth(node):
if not node: return 0
L = depth(node.left)
R = depth(node.right)
self.ans = max(self.ans, L+R+1)
return max(L, R) + 1

depth(root)
return self.ans - 1